# %%调库and建立微分方程
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.integrate import solve_ivp


def diff_equation(t, ylist):
    x, y, p, q = ylist
    return np.array([3*30*(p-x)/((p-x)**2+(q-y)**2)**(0.5), 3*30*(q-y)/((p-x)**2+(q-y)**2)**(0.5), 15*np.cos(np.pi/4), 15*np.sin(np.pi/4)])
# 定义微分方程


# %%设置时间区间后求解数值解
t = np.linspace(0, 30, 10000)

results = solve_ivp(diff_equation, (0., 30.), [
                    0, 0, 20, 0], t_eval=t).y
x, y, m, n = [results[i, :] for i in range(4)]
# %%处理得到的四种数据，删去距离小的
k = np.size(t)
d = 0
for i in range(0, k):
    dd = np.sqrt((x[i]-m[i])**2+(y[i]-n[i])**2)
    if dd <= 0.15:
        index = np.arange(i, k)
        index = index.astype('int64')  # 他奶奶的，这个删除的index用法要求传入的是整数
        # 但是他奶奶的arrange1生成的玩意儿不是整数，搞了我一晚上，气死我了
        x = np.delete(x, index)
        y = np.delete(y, index)
        m = np.delete(m, index)
        n = np.delete(n, index)

        break


# %%画出动态图像
fig = plt.figure(tight_layout=True)

plt.xlim((-1, 30))  # 设置图框的横纵坐标显示范围
plt.ylim((0, 10))

xx, yy, mm, nn = [[] for i in range(4)]  # 把四个变量的结果取出来分别赋给四个一维数组

point_ani1, = plt.plot(xx, yy, "r-")  # 导弹飞行轨迹
point_ani2, = plt.plot(mm, nn, "b-")  # 船航行轨迹

point_ani_ball, = plt.plot(xx, yy, "ro", linewidth=10)

text_pt1 = plt.text(0.5, 9, '', fontsize=13)
text_pt2 = plt.text(0.5, 8, '', fontsize=13)


def update(num):

    xx.append(x[num])
    yy.append(y[num])
    mm.append(m[num])
    nn.append(n[num])
    point_ani1.set_data(xx, yy)
    point_ani2.set_data(mm, nn)
    point_ani_ball.set_data(xx, yy)
    text_pt1.set_text("x=%.3f, y=%.3f" % (x[num], y[num]))
    text_pt2.set_text("m=%.3f, n=%.3f" % (m[num], n[num]))
    return point_ani1, text_pt1, point_ani2, text_pt2,


plt.grid(ls="--")

ani = animation.FuncAnimation(fig=fig,
                              func=update,
                              frames=100,
                              interval=5,
                              blit=True)
plt.show()


# %%下面计算导弹与船相撞点坐标
# k = np.size(t)
# d = 0
# for i in range(0, k):
#     dd = np.abs(x[i]-y[i]-20)/np.sqrt(2)
#     if dd < 0.01:
#         for l in range(1, k):
#             d = np.sqrt((x[l]-x[l-1])**2+(y[l]-y[l-1])**2)+d
#         if d <= 50:
#             print('导弹飞行', d, '单位后击中目标')
#             print('导弹飞行时间为：', 60*(t[k]), '分钟')
#             print('击中点的坐标为：', x[i], y[i])
#             plt.text(x[i], y[i], '击中点', fontsize=13)
#             plt.plot(x[i],y[i],'r*')
#         break

# if d > 50 or dd >= 0.001:
#     print('导弹没有击中船')


# %%
